import { Select, Table } from 'antd';
import React, { useEffect, useRef, useState } from 'react';

import { pagination } from '@/utils/pagination';

import { ListData, SearchData } from '#/entity';

export default function ProSelect<
  ValueType extends {
    key?: string;
    label: React.ReactNode;
    value: string | number;
    file?: string;
    title?: string;
  } = any,
>({
  fetchOptions,
  onClick,
  defaultOptions = [],
}: {
  fetchOptions: (searchData: SearchData) => Promise<ListData<ValueType>>;
  onClick: (record: ValueType) => void;
  defaultOptions?: ValueType[];
}) {
  const selectRef = useRef(null);
  const [value, setValue] = useState<ValueType | undefined>(defaultOptions[0]);
  const [selectOpen, setSelectOpen] = useState(false);
  const [searchData, setSearchData] = useState<SearchData>({
    page: 1,
    take: 10,
  });
  const [loading, setLoading] = useState(false);
  const [tableData, setTableData] = useState<ListData<ValueType>>({
    data: defaultOptions,
    count: defaultOptions.length,
  });

  const columns = [
    {
      title: '图片',
      dataIndex: 'file',
      render: (file:string) => <img src={file} width={60} alt="商品图片" className="object-cover" />,
      width: 80,
    },
    {
      title: '商品名称',
      dataIndex: 'label',
      ellipsis: true,
    },
  ];
  const loadData = () => {
    setLoading(true);
    fetchOptions(searchData)
      .then((newData) => {
        setTableData(newData);
      })
      .finally(() => setLoading(false));
  };

  useEffect(() => {
    if (selectOpen) {
      loadData();
    }
  }, [selectOpen, searchData]);

  const handleDropdownVisibleChange = (open: boolean) => {
    setSelectOpen(open);
  };
  const handleClear = () => {
    setValue(undefined);
    onClick(undefined); // 如果需要通知父组件清除操作
  };

  return (
    <Select
      onClear={handleClear}
      value={value}
      labelInValue={false}
      fieldNames={{ label: 'title', value: 'id' }}
      placeholder="请选择关联商品"
      showSearch={false}
      allowClear
      ref={selectRef}
      open={selectOpen}
      optionLabelProp="title"
      onDropdownVisibleChange={handleDropdownVisibleChange}
      // notFoundContent={loading ? <Spin size="small" /> : null}
      options={tableData?.data}
      // eslint-disable-next-line react/no-unstable-nested-components
      dropdownRender={() => (
        <Table<ValueType>
          style={{ cursor: 'pointer', padding: 20 }}
          size="small"
          rowKey={(_, index) => index}
          columns={columns}
          dataSource={tableData?.data}
          scroll={{ x: 'max-content', y: 400 }}
          onRow={(record) => ({
            onClick: () => {
              setValue({ ...record });
              onClick(record);
              selectRef.current?.blur();
              setSelectOpen(false);
            },
          })}
          pagination={pagination({
            page: searchData, onPageChange: (page, rows) => {
              setSearchData((prev) => ({
                ...prev,
                page,
                take: rows,
              }));
            }, count: tableData?.count
          })}
          loading={loading}
          rowClassName="hover:bg-gray-50"
        />
      )}
    />
  );
}
